package cfm.com.cfmscreen;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.StateListDrawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketListener;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.exceptions.WebsocketNotConnectedException;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.Handshakedata;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.handshake.ServerHandshakeBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import cfm.com.cfmscreen.comm.MyApp;
import cfm.com.cfmscreen.comm.Url;
import cfm.com.cfmscreen.comm.UserInfo;
import okhttp3.OkHttpClient;
import okio.ByteString;


@SuppressWarnings("WrongConstant")
public class MainActivity extends TitleActivity implements OnClickListener {

    private ViewGroup mMoreLayout;  //父布局容器(动态加载的资源图片和文字等布局都将添加在其里面)
    private TextToSpeech tts;
    private List<String> msgs = new ArrayList<>();
    private boolean isFirst = true;
    private int k=0,num=4,n=0;//每行显示几个
    private PowerManager powerManager = null;
    //private Ringtone r;
    private PowerManager.WakeLock wakeLock = null;
    protected BroadcastReceiver mNetworkChangeReceiver;
    protected boolean mIsNetworkChangeReceiverRegistered = false;
    private Timer timer;
    private View mNetErrorView;
    private List<String> sl = new ArrayList();
    private Handler timerHandler=new Handler();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("导管监测");
        showForwardView(true);
        showBackwardView(0, true);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_main);
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        tts = new TextToSpeech(MyApp.getContext(),
                new MyOnInitialListener());
        sl.add("检测设备电量低  ");
        sl.add("报警器电量低  ");
        sl.add("检测设备电量未知,\n");
        sl.add("报警器电量未知,");

        PowerManager pm = (PowerManager) this
                .getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
                | PowerManager.ON_AFTER_RELEASE, "ZAK");
        if (null != wakeLock) {
            wakeLock.acquire();
        }
        setupViews();

        //注册广播用于监听网络状态改变
        mNetworkChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
               detectNetWork();
            }
        };
        timerHandler.postDelayed(myTimerRun, 5000);
    }

    @SuppressLint("NewApi")
    private void setupViews() {
        initSocket();

        getWarnInfors();

        mMoreLayout = (ViewGroup) findViewById(R.id.layout_more);

      //  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
            tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {

                @Override
                public void onStart(String utteranceId) {
                }

                @Override
                public void onDone(String utteranceId) {
                    k++;
                    MainActivity.this.runOnUiThread(new Runnable() {

                        public void run() {

                            if (!msgs.isEmpty()) {
                                if(msgs.size()==1){
                                    tts.speak(msgs.get(0), TextToSpeech.QUEUE_FLUSH, null, "UniqueID");
                                    msgs.clear();
                                    k=0;
                                }else if(msgs.size()>k){
                                    tts.speak(msgs.get(k-1), TextToSpeech.QUEUE_FLUSH, null, "UniqueID");
                                }else if(msgs.size()==k){
                                    tts.speak(msgs.get(k-1), TextToSpeech.QUEUE_FLUSH, null, "UniqueID");
                                    msgs.clear();
                                    k=0;
                                }else{
                                    msgs.clear();
                                    k=0;
                                }
                            } else {
                                k=0;
                                msgs.clear();
                                isFirst = true;
                            }
                        }
                    });
                }

                @Override
                public void onError(String utteranceId) {

                }
            });
    }

    private void getWarnInfors(){

        String httpUrl = Url.baseUrl+Url.warnInfors;
        StringRequest get = new StringRequest(Request.Method.GET, httpUrl+"?hospitalId="+
                UserInfo.getInstance().getHospitalId()+"&areaId="+UserInfo.getInstance().getAreaId(), new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                 refreshUI(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MyApp.getContext(),"网络错误", 100).show();
            }
        });
        MyApp.requestQueue.add(get);
    }

    @SuppressLint("LongLogTag")
    private void addViews(ViewGroup layout, JSONArray categories, int start, int end)
            throws JSONException {

        mMoreLayout.removeAllViews();
        // 表格第一条线
        View.inflate(this, R.layout.layout_line_horizonal, layout);
        for (int i = start; i < end; i++) {
            //找到索引，便于根据索引添加图片文件和文字
            int firstIndex = i * num;
            int secondIndex = firstIndex + 1;
            int thirdIndex = firstIndex + 2;
            int fourIndex = firstIndex + 3;

            JSONObject firstCategory = categories.getJSONObject(firstIndex);
            JSONObject secondCategory = categories.getJSONObject(secondIndex);
            JSONObject thirdCategory = categories.getJSONObject(thirdIndex);
            JSONObject fourCategory = categories.getJSONObject(fourIndex);

            StateListDrawable firstDrawable = new StateListDrawable();
            firstDrawable.addState(new int[]{}, getResources().getDrawable(
                    getImgId(firstCategory,firstIndex)));
//            StateListDrawable dll1 = new StateListDrawable();
//            dll1.addState(new int[]{}, getResources().getDrawable(
//                    getImgDllId(firstCategory,firstIndex)));
//            StateListDrawable sb1 = new StateListDrawable();
//            sb1.addState(new int[]{}, getResources().getDrawable(
//                    getImgSbId(firstCategory,firstIndex)));

            StateListDrawable secondDrawable = new StateListDrawable();
            secondDrawable.addState(new int[]{}, getResources().getDrawable(
                    getImgId(secondCategory,secondIndex)));
//            StateListDrawable dll2 = new StateListDrawable();
//            dll2.addState(new int[]{}, getResources().getDrawable(
//                    getImgDllId(secondCategory,secondIndex)));
//            StateListDrawable sb2 = new StateListDrawable();
//            sb2.addState(new int[]{}, getResources().getDrawable(
//                    getImgSbId(secondCategory,secondIndex)));

            StateListDrawable thirdDrawable = new StateListDrawable();
            thirdDrawable.addState(new int[]{}, getResources().getDrawable(
                    getImgId(thirdCategory,thirdIndex)));
//            StateListDrawable dll3 = new StateListDrawable();
//            dll3.addState(new int[]{}, getResources().getDrawable(
//                    getImgDllId(thirdCategory,thirdIndex)));
//            StateListDrawable sb3 = new StateListDrawable();
//            sb3.addState(new int[]{}, getResources().getDrawable(
//                    getImgSbId(thirdCategory,thirdIndex)));

            StateListDrawable fourDrawable = new StateListDrawable();
            fourDrawable.addState(new int[]{}, getResources().getDrawable(
                    getImgId(fourCategory,fourIndex)));
//            StateListDrawable dll4 = new StateListDrawable();
//            dll4.addState(new int[]{}, getResources().getDrawable(
//                    getImgDllId(fourCategory,fourIndex)));
//            StateListDrawable sb4 = new StateListDrawable();
//            sb4.addState(new int[]{}, getResources().getDrawable(
//                    getImgSbId(fourCategory,fourIndex)));
            // 父布局
            LinearLayout linearLayout = new LinearLayout(this);

            // 第一个子布局
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);
            View.inflate(this, R.layout.layout_department, linearLayout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);

            // 第二个子布局
            View.inflate(this, R.layout.layout_department, linearLayout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);

            // 第三个子布局
            View.inflate(this, R.layout.layout_department, linearLayout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);

            // 第四个子布局
            View.inflate(this, R.layout.layout_department, linearLayout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);

            LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
            layout.addView(linearLayout, layoutParams);

            // 表格最后一条线
            View.inflate(this, R.layout.layout_line_horizonal, layout);
            //根据索引getChildAt到指定的位置
            View firstView = linearLayout.getChildAt(1);
            firstView.setTag(firstCategory.optInt("childId"));        //设置tag，便于在后面判断点击的哪一个
            firstView.setOnClickListener(this);
            TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
            firstTextView.setText(getText(firstCategory.getString("childName")));   //设置文字
            TextView firstTimeTv = (TextView) firstView.findViewById(R.id.tvTime);
            String time1 = firstCategory.getString("warnTime");
            firstTimeTv.setText(getText("最近报警："+time1.substring(5,7)+"/"+time1.substring(8)));

            TextView firstPartTv = (TextView) firstView.findViewById(R.id.tvItem);
            firstPartTv.setText("部位："+getText(firstCategory.getString("item")));

            TextView firstBedTv = (TextView) firstView.findViewById(R.id.text_bed);
            firstBedTv.setText(getText(firstCategory.getString("bed")));
            TextView dll1Tv = (TextView) firstView.findViewById(R.id.tvTip);
            dll1Tv.setText(getDLLText(firstCategory));
            ImageView firstImageView = (ImageView) firstView.findViewById(R.id.image_icon);
            firstImageView.setImageDrawable(firstDrawable);
            ImageView dll1ImageView = (ImageView) firstView.findViewById(R.id.dll_icon);
           // dll1ImageView.setImageDrawable(dll1);
            ImageView sb1ImageView = (ImageView) firstView.findViewById(R.id.sb_icon);
           // sb1ImageView.setImageDrawable(sb1);

            View secondView = linearLayout.getChildAt(3);
            secondView.setTag(secondCategory.optInt("childId"));
            secondView.setOnClickListener(this);
            TextView secondTextView = (TextView) secondView.findViewById(R.id.text_title);
            secondTextView.setText(getText(secondCategory.getString("childName")));
            TextView secondTimeTv = (TextView) secondView.findViewById(R.id.tvTime);
            String time2 = secondCategory.getString("warnTime");
            secondTimeTv.setText(getText("最近报警："+time2.substring(5,7)+"/"+time2.substring(8)));
            TextView secondPartTv = (TextView) secondView.findViewById(R.id.tvItem);
            secondPartTv.setText("部位："+getText(secondCategory.getString("item")));

            TextView secondBedTv = (TextView) secondView.findViewById(R.id.text_bed);
            secondBedTv.setText(getText(secondCategory.getString("bed")));
            TextView dll2Tv = (TextView) secondView.findViewById(R.id.tvTip);
            dll2Tv.setText(getDLLText(secondCategory));
            ImageView secondImageView = (ImageView) secondView.findViewById(R.id.image_icon);
            secondImageView.setImageDrawable(secondDrawable);
            ImageView dll2ImageView = (ImageView) secondView.findViewById(R.id.dll_icon);
           // dll2ImageView.setImageDrawable(dll2);
            ImageView sb2ImageView = (ImageView) secondView.findViewById(R.id.sb_icon);
           // sb2ImageView.setImageDrawable(sb2);

            View thirdView = linearLayout.getChildAt(5);
            thirdView.setTag(thirdCategory.optInt("childId"));
            thirdView.setOnClickListener(this);
            TextView thirdTextView = (TextView) thirdView.findViewById(R.id.text_title);
            thirdTextView.setText(getText(thirdCategory.getString("childName")));
            TextView thirdTimeTv = (TextView) thirdView.findViewById(R.id.tvTime);
            String time3 = thirdCategory.getString("warnTime");
            thirdTimeTv.setText(getText("最近报警："+time3.substring(5,7)+"/"+time3.substring(8)));
            TextView thirdPartTv = (TextView) thirdView.findViewById(R.id.tvItem);
            thirdPartTv.setText("部位："+getText(thirdCategory.getString("item")));

            TextView thirdBedTv = (TextView)thirdView.findViewById(R.id.text_bed);
            thirdBedTv.setText(getText(thirdCategory.getString("bed")));
            TextView dll3Tv = (TextView) thirdView.findViewById(R.id.tvTip);
            dll3Tv.setText(getDLLText(thirdCategory));
            ImageView thirdImageView = (ImageView) thirdView.findViewById(R.id.image_icon);
            thirdImageView.setImageDrawable(thirdDrawable);
            ImageView dll3ImageView = (ImageView) thirdView.findViewById(R.id.dll_icon);
          //  dll3ImageView.setImageDrawable(dll3);
            ImageView sb3ImageView = (ImageView) thirdView.findViewById(R.id.sb_icon);
           // sb3ImageView.setImageDrawable(sb3);

            View fourView = linearLayout.getChildAt(7);
            fourView.setTag(fourCategory.optInt("childId"));
            fourView.setOnClickListener(this);
            TextView fourTextView = (TextView) fourView.findViewById(R.id.text_title);
            fourTextView.setText(getText(fourCategory.getString("childName")));
            TextView fourTimeTv = (TextView) fourView.findViewById(R.id.tvTime);
            String time4 = fourCategory.getString("warnTime");
            fourTimeTv.setText(getText("最近报警："+time4.substring(5,7)+"/"+time4.substring(8)));
            TextView fourPartTv = (TextView) fourView.findViewById(R.id.tvItem);
            fourPartTv.setText("部位："+getText(fourCategory.getString("item")));

            TextView fourBedTv = (TextView) fourView.findViewById(R.id.text_bed);
            fourBedTv.setText(getText(fourCategory.getString("bed")));
            TextView dll4Tv = (TextView) fourView.findViewById(R.id.tvTip);
            dll4Tv.setText(getDLLText(fourCategory));
            ImageView fourImageView = (ImageView) fourView.findViewById(R.id.image_icon);
            fourImageView.setImageDrawable(fourDrawable);
            ImageView dll4ImageView = (ImageView) fourView.findViewById(R.id.dll_icon);
            //dll4ImageView.setImageDrawable(dll4);
            ImageView sb4ImageView = (ImageView) fourView.findViewById(R.id.sb_icon);
            //sb4ImageView.setImageDrawable(sb4);
        }

        categories = null;
    }

    public void initSocket() {
        final String[] txt = {""};
        try {
            URI uri = new URI(Url.socketPath+UserInfo.getInstance().getUserId());
            if (MyApp.mWebSocketClient == null) {
                MyApp.mWebSocketClient = new WebSocketClient(uri) {

                    @Override
                    public void onOpen(ServerHandshake serverHandshake) {

                    }
                    @Override
                    public void onMessage(final String msg) {

                        if(msg.equals("heat")){
                            return;
                        }else{
                            txt[0] = msg;
                            /**try {
                                //JSONObject object = new JSONObject(msg);
                                //object.getString("msg");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }**/
                        }
                        if(!txt[0].contains("正常接入")) {
                            if (!msgs.contains(txt[0])) {
                                msgs.add(txt[0]);
                            }
                        }
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        getWarnInfors();
                                        //refreshUI(msg);
                                    }
                                });
                            }
                        }).start();
                       /** runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                refreshUI(msg);
                            }
                        });**/
                        if (isFirst) {
                            if(!txt[0].contains("正常接入")) {
                                tts.speak(txt[0], TextToSpeech.QUEUE_FLUSH, null, "UniqueID");
                                isFirst = !isFirst;
                            }
                        }
                    }
                    @Override
                    public void onClose(int i, String s, boolean b) {

                        System.out.println("断开连接iii====="+i);
                        n++;
                        if(n==8) {
                            tts.speak("网络故障", TextToSpeech.QUEUE_FLUSH, null, "UniqueID");
                            n=0;
                        }
                        MyApp.mWebSocketClient = null;
                        initSocket();
                    }
                    @Override
                    public void onError(Exception e) {
                        System.out.println("onErrorsss====="+e);
                    }
                };
                MyApp.mWebSocketClient.setConnectionLostTimeout(120);
                try {
                    MyApp.mWebSocketClient.connectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    Runnable myTimerRun=new Runnable(){
        @Override
        public void run() {
            if(MyApp.mWebSocketClient!=null){
                try{
                    MyApp.mWebSocketClient.send("heat");
                }catch (WebsocketNotConnectedException e){
                    System.out.println("mWebSocketClient.isClosed");
                }
            }
            timerHandler.postDelayed(this, 100000);      //再次调用myTimerRun对象，实现每两秒一次的定时器操作
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onClick(View v) {
        final Object tag = v.getTag();
        if (tag != null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    MainActivity.this,AlertDialog.THEME_HOLO_LIGHT);
            builder.setTitle("离院");
            builder.setMessage("病人是否要离院？");
            builder.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            String httpUrl = Url.baseUrl+Url.leaveChild;
                            StringRequest get = new StringRequest(Request.Method.GET, httpUrl+"?childId="+tag.toString()
                                    , new Response.Listener<String>() {

                                @Override
                                public void onResponse(String s) {
                                    mMoreLayout.post(new Runnable() {
                                        @Override
                                        public void run() {
                                         mMoreLayout.removeAllViews();
                                         getWarnInfors();
                                        }
                                    });
                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Toast.makeText(MyApp.getContext(),"网络错误", 100).show();
                                }
                            });
                            MyApp.requestQueue.add(get);
                        }
                    });
            builder.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            //setTitle("点击了对话框上的Button3");
                        }
                    });
            builder.show();
        }
        if(v.getId() == R.id.button_backward){
            if(MyApp.mWebSocketClient!=null) {
                MyApp.mWebSocketClient.close();
            }
            this.wakeLock.release();
            finish();

        }
        if(v.getId() == R.id.button_forward){
          //  r.stop();
        }
    }

    private void refreshUI(String s){
        try {
            JSONObject object = new JSONObject(s);
            JSONArray warnInforsList = object.getJSONArray("warnInforsList");
            System.out.println("warnInforsList=="+warnInforsList);
            int size = warnInforsList.length();
            if(size==0){
                return;
            }else if(size<num){
                for (int k=0;k<num-size;k++){
                    warnInforsList.put(new JSONObject());
                }
            }else{
                int m = size % num;
                if(m!=0){
                    for (int k=0;k<num-m;k++){
                        warnInforsList.put(new JSONObject());
                    }
                }
            }
            addViews(mMoreLayout, warnInforsList, 0, warnInforsList.length() / num);
        } catch (JSONException e) {

        }
    }

    private String getText(String s){

        if(s!=null){
            return s;
        }else{
            return "";
        }
    }

    private String getDLLText(JSONObject obj){

        List<Integer> tl = new ArrayList<>();
        tl.add(obj.optInt("sbDl"));
        tl.add(obj.optInt("bjqDl"));
        int bjqs = obj.optInt("bjqState");
        String s="";
        for(int i=0,l=tl.size();i<l;i++){
            if(tl.get(i)==1){
                s+=sl.get(i);
            }else{
                s+="";
            }
        }
        return s;
    }

    private int getImgId(JSONObject obj,int index) {

        String name = "";
        int dgs = obj.optInt("dgState");
        int sbs = obj.optInt("sbState");
        int bjqs = obj.optInt("bjqState");
        if (bjqs==2) {
            name = "bjqz";
        } else if (bjqs==1){
            name = "bjq";
        }else if (bjqs==3){
            name = "sbw";
        }else{
            if(sbs==1){
                name = "jcsb";
            }else{
                if(dgs==1){
                    name = "yichangs";
                }else{
                    name = "normal";
                }
            }
        }
        return getResources().getIdentifier(String.format(name,
                index + 1), "drawable", getApplicationContext().getPackageName());
    }

    private int getImgDllId(JSONObject obj,int index) {

        int sbDl = obj.optInt("sbDl");
        int bjqDl = obj.optInt("bjqDl");
        if (sbDl==1||bjqDl==1) {
            return getResources().getIdentifier(String.format("dll_icon",
                    index + 1), "drawable", getApplicationContext().getPackageName());
        } else{
            return getResources().getIdentifier(String.format("vodicon",
                    index + 1), "drawable", getApplicationContext().getPackageName());
        }
    }

    private int getImgSbId(JSONObject obj,int index) {

        int sbs = obj.optInt("sbState");
        int bjqs = obj.optInt("bjqState");
        if (sbs==1||bjqs==1) {
            return getResources().getIdentifier(String.format("sb_icon",
                    index + 1), "drawable", getApplicationContext().getPackageName());
        } else {
            return getResources().getIdentifier(String.format("vodicon",
                    index + 1), "drawable", getApplicationContext().getPackageName());
        }
    }

    @SuppressLint("NewApi")
    class MyOnInitialListener implements TextToSpeech.OnInitListener {

        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
            int result = tts.setLanguage(Locale.CHINA);
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Toast.makeText(MainActivity.this, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
            }
            tts.speak("欢迎使用", TextToSpeech.QUEUE_FLUSH, null, "UniqueID");
        }

        }

    }

    protected void detectNetWork() {
        if (!isConnected(this)) {

            mNetErrorView.setVisibility(View.VISIBLE);
            MyApp.mWebSocketClient = null;
            tts.speak("网络故障请检查网络设置", TextToSpeech.QUEUE_FLUSH, null, "UniqueID");
        }else{
            mNetErrorView.setVisibility(View.GONE);
        }
    }

    public void refresh() {

        onCreate(null);

    }
    //判断网络是否连接
    public boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    protected void onResume() {
       // r.stop();
        super.onResume();
        this.wakeLock.acquire();
        MyApp.mWebSocketClient.close();
        MyApp.mWebSocketClient = null;
        initSocket();
        registerReceiver(mNetworkChangeReceiver, new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION));

    }

    protected void onPause() {
        super.onPause();
        this.wakeLock.release();
      /*  r.stop();
        unregisterReceiver(mNetworkChangeReceiver);
        if(timer != null)
        {
            timer.cancel();
            timer = null;
        }*/
    }

    @SuppressLint("NewApi")
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mNetworkChangeReceiver);
        timerHandler.removeCallbacks(myTimerRun);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        System.out.println("onSaveInstanceState=====");
        super.onSaveInstanceState(outState);
    }

    /**
     * Activity被系统杀死后再重建时被调用.
     *
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        System.out.println("onRestoreInstanceState=====");
        super.onRestoreInstanceState(savedInstanceState);
        System.out.println("onRestoreInstanceStatet===="+MyApp.mWebSocketClient);
    }
}
